<template>
  <div class="app-container">
    <div class="filter-container">
      <section>
        <span style="margin-right:10px;">IP</span>
        <el-input
          v-model="ipadmin.listQuery.ip"
          placeholder="IP"
          clearable
          max-width="200"
          style="width: 140px;"
          class="filter-item"
        />
      </section>
      <section class="sectin01">
        <el-select
          v-model="ipadmin.listQuery.status"
          placeholder="类型"
          clearable
          class="filter-item"
          style="width: 130px"
          min-widht="150"
        >
          <el-option
            v-for="item in calendarTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
      </section>
      <section class="sectin01" style="width:'300px'">
        <span style="margin-right:10px;">到期时间</span>
        <el-date-picker
          v-model="value7"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss "
          format="yyyy-MM-dd"
          @change="time02()"
        ></el-date-picker>
      </section>
      <section class="sectin01">
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >搜索</el-button>
      </section>
      <section class="sectin01">
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >新增服务器</el-button>
      </section>
    </div>
    <!-- <div class="tables">

    </div>-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="ipadmin.list || [{}]"
      height="700"
      border
      fit
      highlight-current-row
      :cell-class-name="tableCessClassName"
      style="width: 100%;"
      @sort-change="sortChange"
      :row-class-name="tableRowClassName"
      :default-sort="{order: 'ascending'}"
    >
      <el-table-column type="index" label="序号" prop="id" align="center" width="60"></el-table-column>
      <el-table-column label="IP" align="center" width="120px" prop="ip"></el-table-column>
      <el-table-column label="续费状态" min-width="80">
        <template slot-scope="{row}">
          <el-tag
            :type="row.status_name"
            :class="{'warning':(row.status_name==ipadmin.sign.warning),'outtime':(row.status_name==ipadmin.sign.outtime),'success':(row.status_name==ipadmin.sign.success)}"
          >{{ row.status_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用时段" min-width="200px" align="center" prop="valid_time">
        <template slot-scope="{row}">
          <span>{{ row.valid_time | filterLongTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="报警时间"
        prop="pay_warning_time"
        sortable
        width="160px"
        class-name="warn_time"
        align="center"
      >
        <template slot-scope="{row}">
          <span>{{ row.pay_warning_time | masDateFormat('yyyy-mm-dd')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="到期时间"
        sortable
        width="160px"
        class-name="end_times"
        align="center"
        prop="end_time"
      >
        <template slot-scope="{row}">
          <span>{{ row.end_time | masDateFormat('yyyy-mm-dd') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次续费时间" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.add_time | masDateFormat('yyyy-mm-dd') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handrenew(scope.$index,ipadmin.list[scope.$index].id)"
          >续费</el-button>
          <el-button
            type="danger"
            size="mini"
            @click="handleModifyStatus(scope.$index,ipadmin.list[scope.$index].id)"
          >删除</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleDelete(scope.$index,ipadmin.list[scope.$index].id)"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="ipadmin.listQuery.page"
      :page-sizes="[20, 50, 100, 200]"
      :page-size="20"
      layout="total, sizes, prev, pager, next, jumper"
      :total="ipadmin.total"
    ></el-pagination>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="closeDialog()"
      class="addserve"
    >
      <el-form
        ref="dataForm"
        :rules="rules01"
        :model="ipadmin.temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <h2 v-if="show_ip" style="text-align:center;padding-bottom:20px;letter-spacing:15px;">编辑IP</h2>
        <h2 v-else style="text-align:center;padding-bottom:20px;letter-spacing:15px;">添加IP</h2>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="ipadmin.temp.ip" :disabled="show_ip" />
        </el-form-item>

        <el-form-item label="上次续费时间" prop="add_time">
          <el-date-picker
            v-model="ipadmin.temp.add_time"
            type="datetime"
            placeholder="上次续费时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="到期时间" prop="end_time">
          <el-date-picker
            v-model="ipadmin.temp.end_time"
            type="datetime"
            placeholder="到期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="leave_ip()">离开</el-button>
        <el-button type="primary" @click="createData()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
    <!-- 删除对话框 -->
    <el-dialog title="提示" :visible.sync="centerDialogVisible" width="30%" center>
      <p class="deletes">是否删除</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clear_ip()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 续费对话框 -->
    <el-dialog title="提示" :visible.sync="renewDialogVisible" width="30%" center>
      <p class="deletes">是否续费</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renewDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="renew_ip()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//引入vuex
import { mapState } from "vuex"
import {
  addIps,
  getIpList,
  delIpInfo,
  getupdateIpInfo,
  updateIpInfo,
  renew_ip,
} from "@/api/table"
// import {  getupdateIpInfo } from "@/api/user"
import waves from "@/directive/waves" // waves directive
// import { parseTime } from "@/utils" //时间过滤
import Pagination from "@/components/Pagination" // secondary package based on el-pagination
import ipadmin from "@/store/modules/ipadmin"

const calendarTypeOptions = [
  { key: 0, display_name: "全部续费类型" },
  { key: 1, display_name: "已续费" },
  { key: 2, display_name: "报警中" },
  { key: 3, display_name: "已逾期" },
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    filterLongTime(status = "") {
      // var pattern = /\d{2}:\d{2}:\d{2}/;
      var str = status
      str = str.replace(/\d{2}:\d{2}:\d{2}/g, "")
      return str
    },
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      }
      return statusMap[status]
    },
    masDateFormat: function (msg = "", pattern = "") {
      var mt = new Date(msg)
      var y = mt.getFullYear()
      var m = (mt.getMonth() + 1).toString().padStart(2, "0")
      var d = mt.getDate()
      if (pattern == "yyyy-mm-dd") {
        return y + "-" + m + "-" + d
      }
      return y + "-" + m + "-" + d
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
  },
  computed: {
    ...mapState(["ipadmin"]),
  },
  data() {
    //IP校验规则
    var checkIP = (rule, value, callback) => {
      var IP =
        "^((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}$"
      var patt1 = new RegExp(IP)
      if (!value) {
        return callback(new Error("IP地址不能为空"))
      }
      setTimeout(() => {
        if (!patt1.test(value)) {
          callback(new Error("请输入正确的IP地址"))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      value7: [""],
      centerDialogVisible: false,
      renewDialogVisible: false,
      show_ip: false,
      currentPage4: 1,
      value1: "",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        time: undefined,
        ip: undefined,
        status: undefined,
        sort: "+id",
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        ip: "",
        dueTime: "",
        lastTime: "",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      rules01: {
        ip: [{ validator: checkIP, trigger: "blur" }],
        end_time: [
          { required: true, message: "到期时间不能空", trigger: "blur" },
        ],
        add_time: [
          { required: true, message: "续费时间不能空", trigger: "blur" },
        ],
      },
      downloadLoading: false,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    clear_ip() {
      this.centerDialogVisible = false
      delIpInfo({ id: this.$store.state.ipadmin.delete_ip }).then((res) => {
        this.getList()
        this.$message({
          message: "删除成功",
          type: "success",
        })
      })
    },
    renew_ip() {
      this.renewDialogVisible = false
      renew_ip({ id: this.$store.state.ipadmin.renew_ip }).then((res) => {
        console.log(res.data)
        this.$store.commit("changeList_ip", res.data)
        // this.getList()
        this.$message({
          message: "续费成功",
          type: "success",
        })
      })
    },
    leave_ip() {
      this.dialogFormVisible = false
      this.show_ip = false
      this.$store.commit("cleartemp_ip")
    },
    closeDialog() {
      this.dialogFormVisible = false
      this.show_ip = false
      this.$store.commit("cleartemp_ip")
    },
    // time01() {
    //   console.log(this.value1)
    // },
    time02() {
      // console.log(this.value7)
      if (this.value7) {
        this.$store.commit("serchTime_ip", this.value7)
      } else {
        this.$store.commit("serchTime_ip", ["", ""])
      }
    },
    //获取表格列表
    getList() {
      this.listLoading = true
      getIpList(this.$store.state.ipadmin.listQuery).then((res) => {
        this.list = res.data
        this.$store.commit("list_ip", { list: this.list, total: res.totalSum })
        this.listLoading = false
      })
    },
    handleFilter() {
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.centerDialogVisible = true
      this.$store.commit("deleteStatus_ip", status)
    },
    handrenew(row, status) {
      // console.log(row);
      this.renewDialogVisible = true
      this.$store.commit("renewStatus_ip", { row, status })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === "id") {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id"
      } else {
        this.listQuery.sort = "-id"
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate()
      })
      this.getList()
    },
    createData() {
      var add_time = new Date(this.$store.state.ipadmin.temp.add_time)
      var end_time = new Date(this.$store.state.ipadmin.temp.end_time)
      if (add_time <= end_time) {
        // console.log("上次续费时间大于到期时间")
        this.$refs["dataForm"].validate((valid) => {
          if (this.show_ip) {
            updateIpInfo(this.$store.state.ipadmin.temp).then((res) => {
              if (res.status == 0) {
                this.$message({
                  message: "修改IP信息成功",
                  type: "success",
                })
                this.$store.commit("cleartemp_ip", res.data)
                this.dialogFormVisible = false
                this.show_ip = false
              } else if (res.status == 1) {
                // console.log('操作失败请重试');
                this.$message({
                  message: "操作失败请重试",
                  type: "warning",
                })
              }
            })
          } else {
            if (valid) {
              //调用接口addNewServe
              addIps(this.$store.state.ipadmin.temp).then((res) => {
                if (res.status == 0) {
                  this.$message({
                    message: "添加IP成功",
                    type: "success",
                  })
                  this.$store.commit("cleartemp_ip")
                  this.dialogFormVisible = false
                }
              })
            }
          }
        })
      } else {
        // console.log("上次续费时间小xiao于到期时间")
        this.$message({
          message: "上次续费时间不能大于到期时间",
          type: "warning",
        })
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = "update"
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate()
      })
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
        }
      })
    },
    handleDelete(row, index) {
      getupdateIpInfo({ id: index }).then((res) => {
        this.$store.commit("getIpSign_ip", res.data)
        this.dialogFormVisible = true
        this.show_ip = true
        this.$store.commit("getTempId_ip", { index, row })
        // this.getList()
        //清除校验信息
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate()
        })
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleSizeChange(e) {
      this.$store.commit("changelimit_ip", e)
      this.getList()
    },
    handleCurrentChange(e) {
      this.$store.commit("changepage_ip", e)
      this.getList()
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? "ascending" : "descending"
    },
    // tableRowStyle({row,rowIndex}){
    //     if (rowIndex%2) {
    //       return "background: 'oldlace';";
    //     } else{
    //       return "background: '#f0f9eb';";
    //     }
    // },
    tableCessClassName({ row, column, rowIndex, columnIndex }) {
      // console.log({ row, column, rowIndex, columnIndex })
      var time01 = this.$store.state.ipadmin.list[rowIndex].pay_warning_time
      var days = this.countDay(time01)
      if (days <= 7 && columnIndex == 4) {
        return "red_ip"
      }
      var time02 = this.$store.state.ipadmin.list[rowIndex].end_time
      var days01 = this.countDay(time02)
      if (days01 <= 3 && columnIndex == 5) {
        return "red_ip"
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return "warning-row"
      } else {
        return "success-row"
      }
      // var time01 = this.$store.state.ipadmin.list[rowIndex].pay_warning_time
      // var time02 = this.$store.state.ipadmin.list[rowIndex].end_time

      // var days = this.countDay(time01)
      // var days01 = this.countDay(time02)
      // // console.log(days, days01)

      // if (days <= 7) {
      //   if (days01 <= 3) {
      //     return "warning-row01"
      //   }
      //   return "warning-row"
      // } else {
      //   return "warning-row02"
      // }
      // return ""
    },
    //计算天数
    countDay(time01 = "") {
      time01 = time01.replace(/\d{2}:\d{2}:\d{2}/g, "") //数组时间
      //当前时间
      var now = new Date()
      var year = now.getFullYear() //得到年份
      var month = now.getMonth() //得到月份
      var date = now.getDate() //得到日期
      month = month + 1
      if (month < 10) month = "0" + month
      if (date < 10) date = "0" + date
      var time = ""
      time = year + "-" + month + "-" + date

      //计算天数
      var sDate1 = Date.parse(time)
      var sDate2 = Date.parse(time01)
      var dateSpan = sDate2 - sDate1
      // dateSpan = Math.abs(dateSpan)
      var iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
      return iDays
    },
  },
}
</script>
<style lang='less' scoped>
.filter-container {
  display: flex;
  // justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  .sectin01 {
    margin-left: 20px;
  }
}
.addserve {
  /deep/.el-input {
    width: 80%;
    text-align: center;
    font-weight: bold;
    color:red;
  }
}

.success {
  color: #67c23a;
}
.warning {
  color: #e6a23c;
}
.outtime {
  color: #f56c6c;
}
/deep/.el-pagination {
  z-index: 999;
  padding-top: 10px;
  height: 50px;
  width: 100%;
  margin-top: 10px;
  margin-left: 10px;
  background-color: #fff;
  position: fixed;
  bottom: 0%;
}
/deep/.el-table .red_ip {
  color: #f56c6c !important;
}
.tables {
  background-color: pink;
  height: 80%;
}
/deep/.el-table {
  padding-bottom: 50px;
}
.app-container {
  padding-bottom: 50px;
}
</style>